﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using A2DFramework.EsbService;
using A2DFramework.ServiceLocatorService;
using System.ServiceModel;
using System.Reflection;

namespace A2DFramework.ESBServerConsole
{
    class EsbRequestsHandler : IRequestHandlerWorker,
        IRequestHandler<EsbRequestWrapper, EsbResponseWrapper>
    {
        public EsbResponseWrapper Handle(EsbRequestWrapper cmd)
        {
            Location location = ServiceLocator.Locate(cmd.CallContractNamespace, cmd.CallContract, cmd.Version);
            Console.WriteLine("location: "+location.Url);


            NetTcpBinding binding = new NetTcpBinding();
            binding.ReceiveTimeout = new TimeSpan(0, 10, 0);
            binding.Security.Mode = SecurityMode.None;
            binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;
            EndpointAddress address = new EndpointAddress(location.Url);

            EsbResponseWrapper response = new EsbResponseWrapper();

            Assembly ass = Assembly.LoadFrom(location.AssemblyPath);
            Type callingContractType = ass.GetType(string.Format("{0}.{1}", cmd.CallContractNamespace, cmd.CallContract));

            Type type = typeof(ChannelFactory<>);
            type = type.MakeGenericType(callingContractType);
            var factory = Activator.CreateInstance(type, binding, address);

            var mi = factory.GetType().GetMethods().Where(t => t.Name == "CreateChannel"&&t.GetParameters().Length==0).First();
            var srv = mi.Invoke(factory, null);

            mi=callingContractType.GetMethod(cmd.Method2Invoke);
            try
            {
                response.Result = mi.Invoke(srv, cmd.Arguments.ToArray());
                response.IsSuccessful = true;
                Console.WriteLine("Successful");
            }
            catch(Exception ex)
            {
                response.IsSuccessful = false;
                Console.WriteLine("调用WCF服务失败: "+ex.Message);
            }
            
            return response;
        }
    }
}
